package com.cjjd.c.feature.mine.login;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cjjd.c.App;
import com.cjjd.c.EventBusKeys;
import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.BaseActivity;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.LoginBean;
import com.cjjd.c.bean.WxLoginAccessTokenBean;
import com.cjjd.c.feature.mine.forgetpsd.ForgetPsdActivity;
import com.cjjd.c.feature.mine.register.RegisterActivity;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.SharePrefUtil;
import com.cjjd.c.utils.StringUtil;
import com.cjjd.c.utils.ToastUtil;
import com.cjjd.c.view.MyEditText;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * ----------------------------------
 * Created by xyd on 2017/8/9.
 * <p/>
 * 描  述：
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class LoginActivity extends BaseActivity {

    @Bind(R.id.et_mobile)
    MyEditText etMobile;
    @Bind(R.id.et_psd)
    MyEditText etPsd;

    @Bind(R.id.button)
    Button button;
    @Bind(R.id.tv_client_type)
    TextView tvClientType;

    @Bind(R.id.btn_login)
    ImageView btnLogin;
    @Bind(R.id.tv_other_login_style)
    TextView tvOtherLoginStyle;
    @Bind(R.id.rl_orther_login)
    RelativeLayout rlOrtherLogin;


    public static final int TYPE_PERSONAL = 0x00000001;
    public static final int TYPE_COMPANY = 0x00000002;

    private int Type = TYPE_PERSONAL;

    @Override
    public Fragment getContentFragment() {
        return null;
    }

    @Override
    public int getContentView() {
        return R.layout.activity_login;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        //processIntentData();
        initView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
        if (EventBusKeys.login.equals(event)) {
            LogUtil.e("xyd", "已经登录");
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBeanEvent(WxLoginAccessTokenBean event) {
        if (event != null) {
            LogUtil.e("xyd", "有接收到");
            wechatLogin(event);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    private void initView() {

    }

    private void changeType() {
        Type = Type == TYPE_COMPANY ? TYPE_PERSONAL : TYPE_COMPANY;
        if (Type == TYPE_COMPANY) {
            tvClientType.setText("个人用户");
            rlOrtherLogin.setVisibility(View.GONE);
            Drawable compDrawable = mContext.getResources().getDrawable(R.drawable.icon_login_comp);
            compDrawable.setBounds(0, 0, compDrawable.getMinimumWidth(), compDrawable.getMinimumHeight());
            etMobile.setCompoundDrawables(compDrawable, null, null, null);
            etMobile.setHint("请输入单位协议酒店账号");
            etMobile.setInputType(InputType.TYPE_CLASS_TEXT);
        } else {
            tvClientType.setText("单位用户");
            rlOrtherLogin.setVisibility(View.VISIBLE);
            Drawable personDrawable = mContext.getResources().getDrawable(R.drawable.icon_login_phone);
            personDrawable.setBounds(0, 0, personDrawable.getMinimumWidth(), personDrawable.getMinimumHeight());
            etMobile.setCompoundDrawables(personDrawable, null, null, null);
            etMobile.setHint("请输入您的手机号");
            etMobile.setInputType(InputType.TYPE_CLASS_PHONE);
        }
    }

    @OnClick({R.id.button, R.id.tv_client_type, R.id.btn_login, R.id.tv_register,
            R.id.tv_forget_psd, R.id.iv_login_wx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.button:
                mContext.onBackPressed();
                break;
            case R.id.tv_client_type:
                changeType();
                break;

            case R.id.tv_register:
                Intent intent = new Intent(mContext, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_forget_psd:
                Intent intent1 = new Intent(mContext, ForgetPsdActivity.class);
                startActivity(intent1);
                break;
            case R.id.btn_login:
                if (Type == TYPE_COMPANY) {
                    // 企业用户登录
                    doLoginCom();
                } else {
                    // 个人用户登录
                    doLogin();
                }
                break;
            case R.id.iv_login_wx:
                sendWxLoginReq();
                break;


        }
    }

    private void sendWxLoginReq() {

     /*
     微信登录的整体流程：
     1. 第三方发起微信授权登录请求，微信用户允许授权第三方应用后，微信会拉起应用或重定向到第三方网站，
          并且带上授权临时票据code参数；
     2. 通过code参数加上AppID和AppSecret等，通过API换取access_token；
     3. 通过access_token进行接口调用，获取用户基本数据资源或帮助用户实现基本操作。
     */

        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "jiudianhui_wx_login";
        App.WX_API.sendReq(req);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        processIntentData();
    }

    private void processIntentData() {
        WxLoginAccessTokenBean wxLoginAccessTokenBean = (WxLoginAccessTokenBean) getIntent().getSerializableExtra("openId");
        if (wxLoginAccessTokenBean != null) {
            wechatLogin(wxLoginAccessTokenBean);
        }
    }

    private void wechatLogin(final WxLoginAccessTokenBean bean) {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("openid", bean.openid);
        Call<HttpResult<LoginBean>> call = service.wechatLogin(JsonUtils.convertParam("wechatLogin", h1));
        call.enqueue(new Callback<HttpResult<LoginBean>>() {
            @Override
            public void onResponse(Call<HttpResult<LoginBean>> call, Response<HttpResult<LoginBean>> response) {
                if (response.isSuccess()) {
                    if (response.body().getReturn_code() == 0) {
                        // 成功登录,保存登录信息
                        LoginBean loginBean = response.body().getData();
                        SharePrefUtil.saveBoolean(mContext, ShareKeys.isLogin, true);
                        SharePrefUtil.saveString(mContext, ShareKeys.Token, loginBean.token);
                        SharePrefUtil.saveString(mContext, ShareKeys.sessionId, loginBean.sessionId);
                        SharePrefUtil.saveString(mContext, ShareKeys.customerUuid, loginBean.customerUuid);
                        finish();
                    } else if (response.body().getReturn_code() == 5) {
                        // 未绑定手机号用户, 引导用户去绑定手机号
                        Intent wxLoginSetMobileIntent = new Intent(mContext, WxLoginSetMobileActivity.class);
                        wxLoginSetMobileIntent.putExtra("openId", bean);
                        startActivity(wxLoginSetMobileIntent);
                    } else {
                        ToastUtil.showToast(response.body().getMessage());
                    }
                }
            }

            @Override
            public void onFailure(Call<HttpResult<LoginBean>> call, Throwable t) {

            }
        });
    }

    private void doLoginCom() {
        mobile = etMobile.getText().toString().trim();
        psd = etPsd.getText().toString().trim();

        if (TextUtils.isEmpty(mobile)) {
            ToastUtil.showLongToast(mContext, "请输入酒店账号!");
            return;
        }

        if (TextUtils.isEmpty(psd)) {
            ToastUtil.showLongToast(mContext, "请输入密码！");
            return;
        }

        HashMap<String, Object> h1 = new HashMap<>();
        //
        h1.put("loginName", mobile);
        h1.put("password", StringUtil.getMD5(psd));


        Call<HttpResult<LoginBean>> customerToLogin = service.companyUserToLogin(JsonUtils.convertParam("companyUserToLogin", h1));
        customerToLogin.enqueue(new CallbackImpl<LoginBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<LoginBean>> call, Response<HttpResult<LoginBean>> response) {
                LoginBean loginBean = response.body().getData();


                SharePrefUtil.saveBoolean(mContext, ShareKeys.isLogin, true);
                SharePrefUtil.saveString(mContext, ShareKeys.Token, loginBean.token);
                SharePrefUtil.saveString(mContext, ShareKeys.sessionId, loginBean.sessionId);
                SharePrefUtil.saveString(mContext, ShareKeys.customerUuid, loginBean.customerUuid);


                onBackPressed();
            }


        });
    }

    private String mobile;
    private String psd;


    private void doLogin() {
        mobile = etMobile.getText().toString().trim();
        psd = etPsd.getText().toString().trim();

        if (!StringUtil.isMobile(mobile)) {
            ToastUtil.showLongToast(mContext, "请输入正确的手机号!");
            return;
        }

        if (TextUtils.isEmpty(psd)) {
            ToastUtil.showLongToast(mContext, "请输入密码！");
            return;
        }

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("loginName", mobile);
        h1.put("password", StringUtil.getMD5(psd));


        Call<HttpResult<LoginBean>> customerToLogin = service.customerToLogin(JsonUtils.convertParam("customerToLogin", h1));
        customerToLogin.enqueue(new CallbackImpl<LoginBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<LoginBean>> call, Response<HttpResult<LoginBean>> response) {
                LoginBean loginBean = response.body().getData();

                SharePrefUtil.saveBoolean(mContext, ShareKeys.isLogin, true);
                SharePrefUtil.saveString(mContext, ShareKeys.Token, loginBean.token);
                SharePrefUtil.saveString(mContext, ShareKeys.sessionId, loginBean.sessionId);
                SharePrefUtil.saveString(mContext, ShareKeys.customerUuid, loginBean.customerUuid);

                finish();
            }


        });

    }
}
